<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth',[
           'except' => ['store','confirm']
        ]);
    }
    public function index()
    {
        $users=User::paginate(10);
        return view('users.index',compact('users'));
    }

    public function store(Request $request)
    {
        $this->validate($request,[
           'name' => 'required',
           'email' => 'required|email',
           'password' => 'required|confirmed',
        ]);
        $user=new User();
        $user->name=$request->name;
        $user->email=$request->email;
        $user->password=bcrypt($request->password);
        $user->save();

        $this->sendEmail($user);
        session()->flash('success','已发送验证邮件啦！');
        return back();

    }

    public function show(User $user)
    {
        $blogs=$user->feed()->orderBy('created_at','desc')->paginate(5);
        return view('users.show',compact('user','blogs'));
    }

    public function edit(User $user)
    {
        $this->authorize('edit',$user);
        return view('users.edit',compact('user'));
    }

    public function update(Request $request,User $user)
    {

        $this->validate($request,[
           'name' => 'required',
            'password' => 'confirmed'
        ]);
        if($request->password){
           $user->name=$request->name;
           $user->password=bcrypt($request->password);
           $user->save();
        }else{
            $user->name=$request->name;
            $user->save();
        }
        return redirect()->route('users.show',$user);
    }

    public function destroy(User $user)
    {
        $this->authorize('destroy',$user);
        $user->delete();
        session()->flash('success','删除成功哦～');
        return back();
    }

    public function sendEmail($user)
    {
        $view='emails.register';
        $data=compact('user');
        $from='1@qq.com';
        $name='1';
        $to=$user->email;
        $subject="邮件已经发送，请注意查收";

        Mail::send($view,$data,function($message) use ($from,$name,$to,$subject){
            $message->from($from,$name)->to($to)->subject($subject);
        });
    }

    public function confirm($token)
    {
        $user=User::where('token',$token)->firstOrFail();

        $user->token=null;
        $user->state=true;
        $user->save();

        session()->flash('success','激活成功哟～');
        Auth::login($user);
        return redirect()->route('users.show',$user);
    }
}
